package com.wqr.it.ecwdr.client.config;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.methods.GetMethod;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSONArray;
import com.wqr.it.ecwdr.client.dto.CountryDto;

@Configuration
public class SysService {
	@Value("${ecwdr.server.url.sys.country}")
	private String sysCountryUrl;
	@Value("${ecwdr.client.name}")
	private String ecwdrClientName;
	private static String charset = "UTF-8";

	@Bean
	public Map<String, CountryDto> countryMap() {
		System.out.println(sysCountryUrl);
		HttpClient client = new HttpClient();
		HttpMethod get = new GetMethod(sysCountryUrl);
		try {
			client.executeMethod(get);
		} catch (HttpException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		BufferedReader in = null;
		try {
			in = new BufferedReader(new InputStreamReader(get.getResponseBodyAsStream(), charset));
		} catch (IOException e) {
			e.printStackTrace();
		} 
        StringBuffer sb = new StringBuffer();
        String str = null;
        if (in != null) {
	        do {
	        	str = null;
	        	try {
					str = in.readLine();
				} catch (IOException e) {
					e.printStackTrace();
				}
	        	if (str != null && !str.equals("\n")) {
	        		sb.append(str + "\n");
	        	}
	        } while (str != null);
        }
        String json = sb.toString().trim();
        System.out.println(json);
        Map<String, CountryDto> map = new ConcurrentHashMap<>();
        
        if (!StringUtils.isEmpty(json)) {
        	List<CountryDto> array = JSONArray.parseArray(json, CountryDto.class);
        	for (CountryDto countryDto : array) {
        		map.put(countryDto.getCode(), countryDto);
        		map.put(countryDto.getId() + "", countryDto);
			}
        }
        return map;
	}
	
	@Bean
	public String ecwdrClientName() {
		return ecwdrClientName;
	}
}
